package com.elibrary;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import nimo.elibrary.actions.User;
import nimo.elibrary.json.model.book.Book;

/**
 * Created with IntelliJ IDEA.
 * User: Enkuso
 * Date: 1/18/13
 * Time: 12:55 PM
 * To change this template use File | Settings | File Templates.
 */
public class MainActivity extends BaseActivity {

    ProgressDialog mDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        if (savedInstanceState == null) {
            // Do first time initialization -- add initial fragment.
            Fragment newFragment = new MainMenuFragment(mStackLevel);
            FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
            ft.add(R.id.main_fragment, newFragment).commit();
        } else {
            mStackLevel = savedInstanceState.getInt("level");
        }

        booklistFragment = new BooklistFragment(++mStackLevel, new Book[]{});

        currentFragment = Constants.FRAGMENT_MAINMENU;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt("level", mStackLevel);
    }

    public void Login(View btn)
    {
        EditText username = (EditText) findViewById(R.id.etUsername);
        EditText password = (EditText) findViewById(R.id.etPassword);
        //TextView tvError = (TextView) findViewById(R.id.tvError);
        if(hasInternetConnection())
            new SigninTask().execute(username.getText().toString(), password.getText().toString());
        //nimo.elibrary.json.model.user.User signedUser = User.Signin(username.getText().toString(), password.getText().toString());
        //if(signedUser != null){
        //    // Амжилттай нэвтэрсэн талаар мэдээлэх
        //    Toast.makeText(this, R.string.signin_success, Toast.LENGTH_SHORT).show();
        //    // Нэвтэрсэн хэрэглэгчийн мэдээлэл утсанд хадгалах
        //    userDataSource.open();
        //    userDataSource.createOrUpdateUser(username.getText().toString(), null, password.getText().toString(),signedUser.token,null,null);
        //    userDataSource.close();
        //
        //    app.setLoggedIn(signedUser.token);
        //
        //    setSignoutMenuBtn();
        //    //finish();
        //} else {
        //    setTvErrorMessage(R.string.signin_error);
        //}

        InputMethodManager imm = (InputMethodManager)getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
    }

    public void Signup(View btn)
    {
        EditText username = (EditText) findViewById(R.id.etUsername);
        EditText email = (EditText) findViewById(R.id.etEmailAddress);
        EditText password = (EditText) findViewById(R.id.etPassword);
        //TextView tvError = (TextView) findViewById(R.id.tvError);
        if(hasInternetConnection())
            new SignupTask().execute(username.getText().toString(), email.getText().toString(), password.getText().toString());
        //nimo.elibrary.json.model.user.User signedUser = User.Signup(username.getText().toString(), email.getText().toString(), password.getText().toString());
        //if(signedUser != null){
        //    // Амжилттай бүртгүүлсэн талаар мэдээлэх
        //    Toast.makeText(this, R.string.signup_success, Toast.LENGTH_SHORT).show();
        //    // Нэвтэрсэн хэрэглэгчийн мэдээлэл утсанд хадгалах
        //    userDataSource.open();
        //    userDataSource.createOrUpdateUser(username.getText().toString(), null, password.getText().toString(),signedUser.token,null,null);
        //    userDataSource.close();
        //
        //    app.setLoggedIn(signedUser.token);
        //
        //    setSignoutMenuBtn();
        //
        //    finish();
        //} else {
        //    setTvErrorMessage(R.string.signup_error);
        //}

        InputMethodManager imm = (InputMethodManager)getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(username.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(email.getWindowToken(), 0);
        imm.hideSoftInputFromWindow(password.getWindowToken(), 0);
    }

    public void ResetPassword(View btn)
    {
        EditText email = (EditText) findViewById(R.id.etEmailAddress);
        //TextView tvError = (TextView) findViewById(R.id.tvError);
        //ProgressDialog progressDialog = new ProgressDialog(this);
        //progressDialog.setMessage("Please wait...");
        //progressDialog.show();
        //new GetTask(this).execute(email.getText().toString());
        if(hasInternetConnection())
            new ResetPasswordTask().execute(email.getText().toString());

        //boolean resetPwdResult = User.ResetPassword(email.getText().toString());
        //if(resetPwdResult){
        //    Toast.makeText(this, R.string.reset_password_success, Toast.LENGTH_SHORT).show();
        //
        //    InputMethodManager imm = (InputMethodManager)getSystemService(
        //            Context.INPUT_METHOD_SERVICE);
        //    imm.hideSoftInputFromWindow(email.getWindowToken(), 0);
        //    getSupportFragmentManager().popBackStackImmediate();
        //} else {
        //    tvError.setText(R.string.reset_password_error);
        //}

        InputMethodManager imm = (InputMethodManager)getSystemService(
                Context.INPUT_METHOD_SERVICE);
        imm.hideSoftInputFromWindow(email.getWindowToken(), 0);

        //progressDialog.dismiss();
    }

    class GetTask extends AsyncTask<String, Void, Boolean> {

        Context cntxt;
        ProgressDialog mDialog;

        GetTask(Context cntxt)
        {
            this.cntxt = cntxt;
        }

        @Override
        protected void onPreExecute() {
            taskPreExecute();
            //mDialog = new ProgressDialog(cntxt); //taking object for progress dialog
            //mDialog.setMessage("Please wait...");
            //mDialog.show(); //Displaying progressDialog
        }

        @Override
        protected Boolean doInBackground(String... params) {

            //do the background process
            boolean resetPwdResult = User.ResetPassword(params[0]);

            return resetPwdResult;

        }

        @Override
        protected void onPostExecute(Boolean result) {
            if(result){
                Toast.makeText(MainActivity.this, R.string.reset_password_success, Toast.LENGTH_SHORT).show();

                getSupportFragmentManager().popBackStackImmediate();
            } else {
                setTvErrorMessage(R.string.reset_password_error);
            }
            taskPostExecute();
        }
    }

    class ResetPasswordTask extends AsyncTask<String, String, Boolean> {
        private boolean resetPwdResult;
        @Override
        protected void onPreExecute() {
            taskPreExecute();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            resetPwdResult = User.ResetPassword(params[0]);
            //publishProgress(params[0]);
            return resetPwdResult;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            taskPostExecute();
            if(resetPwdResult){
                Toast.makeText(MainActivity.this, R.string.reset_password_success, Toast.LENGTH_SHORT).show();
                getSupportFragmentManager().popBackStackImmediate();
            } else {
                setTvErrorMessage(R.string.reset_password_error);
            }
        }
    }

    class SigninTask extends AsyncTask<String, Void, nimo.elibrary.json.model.user.User> {
        private String pwd;
        private String uname;
        private nimo.elibrary.json.model.user.User signedUser;

        @Override
        protected void onPreExecute() {
            taskPreExecute();
        }

        @Override
        protected nimo.elibrary.json.model.user.User doInBackground(String... params) {
            uname = params[0];
            pwd = params[1];
            signedUser = User.Signin(uname, pwd);
            return signedUser;
        }

        @Override
        protected void onPostExecute(nimo.elibrary.json.model.user.User result) {
            if(signedUser != null){
                // Амжилттай нэвтэрсэн талаар мэдээлэх
                Toast.makeText(MainActivity.this, R.string.signin_success, Toast.LENGTH_SHORT).show();
                // Нэвтэрсэн хэрэглэгчийн мэдээлэл утсанд хадгалах
                userDataSource.open();
                userDataSource.createOrUpdateUser(uname, null, pwd, signedUser.token,null,null);
                userDataSource.close();

                app.setLoggedIn(signedUser.token);

                setSignoutMenuBtn();

                getSupportFragmentManager().popBackStackImmediate();
            } else {
                setTvErrorMessage(R.string.signin_error);
            }

            taskPostExecute();
        }
    }

    class SignupTask extends AsyncTask<String, Void, nimo.elibrary.json.model.user.User> {
        private String pwd;
        private String uname;
        private String email;
        private nimo.elibrary.json.model.user.User signedUser;

        @Override
        protected void onPreExecute() {
            taskPreExecute();
        }

        @Override
        protected nimo.elibrary.json.model.user.User doInBackground(String... params) {
            uname = params[0];
            email = params[1];
            pwd = params[2];
            signedUser = User.Signin(uname, pwd);
            return signedUser;
        }

        @Override
        protected void onPostExecute(nimo.elibrary.json.model.user.User result) {
            if(signedUser != null){
                // Амжилттай нэвтэрсэн талаар мэдээлэх
                Toast.makeText(MainActivity.this, R.string.signin_success, Toast.LENGTH_SHORT).show();
                // Нэвтэрсэн хэрэглэгчийн мэдээлэл утсанд хадгалах
                userDataSource.open();
                userDataSource.createOrUpdateUser(uname, email, pwd, signedUser.token,null,null);
                userDataSource.close();

                app.setLoggedIn(signedUser.token);

                setSignoutMenuBtn();

                getSupportFragmentManager().popBackStackImmediate();
            } else {
                setTvErrorMessage(R.string.signin_error);
            }

            taskPostExecute();
        }
    }

}
